from turbogears.widgets import Widget
from turbogears import identity
from mnemoply.model.auth import Menu
import time, copy



class menu(object):
    mainmenu=[]
    _instance = None

    @classmethod
    def instance(cls, select):
        if cls._instance is None or Menu.is_need_recreate():
            cls._instance = menu(select)
        return cls._instance

    def __init__(self, select):
        self.mainmenu = self.create_menu(select)

    def create_menu(self,select):
        mainmenu = []
        items ={}
        for menu in select:
            item=dict(
                      gr = menu._get_name_groups(),
                      href=menu.href,
                      name=menu.name,
                      id = menu.id,
                      ordinal=menu.ordinal,
                      )
            exist = items.has_key(menu.id)
            items[menu.id] = item
            if not exist:
                items[menu.id]['subs']=[]
            
            if menu.parent is None:
                mainmenu+= [items[menu.id]]
            else:
                if not items.has_key(menu.parentID):
                    items[menu.parentID]=dict(subs=[])
                items[menu.parentID]['subs'] +=[item]
        return mainmenu
    
    #def create_menu1(self):
    #    select = list( Menu.select(orderBy=['parent_id','ordinal']))
    #    mainmenu = []
    #    items ={}
    #    for menu in select:
    #        item=dict(id=menu.id, menu=menu,subs=[])
    #        if not items.has_key(menu.id):
    #            items[menu.id] = item
    #        else:
    #            items[menu.id]['menu']=menu
    #            items[menu.id]['id'] = menu.id
    #        if menu.parent is None:
    #            mainmenu+= [items[menu.id]]
    #        else:
    #            if not items.has_key(menu.parentID):
    #                items[menu.parentID]=dict(subs=[])
    #            items[menu.parentID]['subs'] +=[item]
    #    return mainmenu

    def check_one_permission(self,menu):
        href = menu['href']
        if href is None or not href.strip():
            return True
        user_groups = set(identity.current.user._get_name_groups())
        menu_groups = set(menu['gr'])
        return  ('dba' in user_groups ) or (menu_groups & user_groups)

    def get_menu_with_permission(self):
        result = copy.deepcopy(self)
        return [m for m in result.mainmenu if result.check_permission(m)]
    
    def check_permission(self,one_menu):
        if not one_menu['subs']:
            return self.check_one_permission(one_menu)
        subs = [m for m in one_menu['subs'] if self.check_permission(m)]
        one_menu['subs'] = subs
        return len(subs)